/**
 * 
 */
package pt.mleiria.crypto;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

import pt.mleiria.bit.Utils;
import pt.mleiria.messages.MessageVO;

/**
 * @author NB13712
 * 
 */
public class Des implements CipherAlgorithms {

	private MessageVO msg;
	private SecretKey desKey;
	
	public Des() {
		KeyGenerator keygenerator;
		try {
			keygenerator = KeyGenerator.getInstance("DES");
			this.desKey = keygenerator.generateKey();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see pt.mleiria.crypto.Cipher#encryptText()
	 */
	public void encryptText() {
		msg.setMessageDigest(encryptOrDecrypt(msg.getMessage(), desKey, Cipher.ENCRYPT_MODE));
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see pt.mleiria.crypto.Cipher#decryptText()
	 */
	public void decryptText() {
		msg.setMessage(encryptOrDecrypt(msg.getMessageDigest(), desKey, Cipher.DECRYPT_MODE));

	}

	private static String encryptOrDecrypt(final String input, final SecretKey myDesKey, final int mode){
		try{
			Cipher desCipher;
			// Create the cipher
			desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
	
			switch (mode) {
			case Cipher.ENCRYPT_MODE:
				// Initialize the cipher for encryption
				desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
				// sensitive information
				byte[] textToEncrypt = input.getBytes("UTF-8");
				// Encrypt the text
				byte[] textEncrypted = Utils.encodeBase64(desCipher.doFinal(textToEncrypt));
				return new String(textEncrypted, "UTF-8");
			case Cipher.DECRYPT_MODE:
				// Initialize the same cipher for decryption
				desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
				byte[] textToDecrypt = Utils.decodeBase64(input.getBytes("UTF-8"));
				// Decrypt the text
				byte[] textDecrypted = desCipher.doFinal(textToDecrypt);
				return new String(textDecrypted, "UTF-8");
			default:
				throw new IllegalArgumentException("Unknown mode!!");
			}
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} 
		return "";
	}
	public void setMessageVO(MessageVO msg) {
		this.msg = msg;
	}
	public MessageVO getMessageVO(){
		return this.msg;
	}

}
